<script>
export default {
  name: 'BiGridSelect',
  props: {
    idField: {
      type: String,
      default: 'id'
    },
    multiple: {
      type: Boolean
    },
    value: {
      type: [Array, String]
    }
  },
  computed: {
    valueIds () {
      let ids = []
      if (Array.isArray(this.value)) {
        ids = this.value
      } else {
        if (this.value) {
          ids.push(this.value)
        }
      }
      return ids
    },
    innerValue: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    }
  },
  events: {
    UiGridCreated (context) {
      context.setIdField(this.idField)
      context.setMultiple(this.multiple)
      context.setSelectable(true)
    }
  },
  methods: {
    handleSelectChange ({ row }) {
      this.selection = [row]
    },
    handleSelectionChange ({ selection }) {
      this.selection = selection
    },
    getGridInstance () {
      let rs = null
      const loop = ($vms, level) => {
        if (!$vms || !$vms.length) {
          return
        }
        if (level > 3) { // 超过3个层级就不再找了，影响性能
          return
        }
        return $vms.some((v) => {
          if (v.$options && v.$options.name === 'UiGrid') {
            rs = v
            return true
          }
          if (loop(v.$children, level + 1)) {
            return true
          }
        })
      }
      loop(this.$children, 0)
      return rs
    },
    getCrossRows (data, crossIds) {
      const rs = []
      if (!data || !data.length || !crossIds || !crossIds.length) {
        return rs
      }
      data.forEach(v => {
        if (crossIds.includes(v[this.idField])) {
          rs.push(v)
        }
      })
      return rs
    },
    getJoinValues (data, selection, valueIds) {
      valueIds = valueIds ? [...valueIds] : []
      if (data && data.length) {
        data.forEach(v => {
          const valueIndex = valueIds.indexOf(v[this.idField])
          if (valueIndex >= 0) {
            valueIds.splice(valueIndex, 1)
          }
        })
      }
      return (selection || []).map(v => v[this.idField]).concat(valueIds)
    }
  },
  mounted () {
    this.$grid = this.getGridInstance()
    if (!this.$grid) {
      throw new Error('[GridSelect] 没有找到Grid组件')
    }
    this.$grid.$on('loaded', ({ data }) => {
      const crossRows = this.getCrossRows(data, this.valueIds)
      if (crossRows && crossRows.length) {
        if (this.multiple) {
          this.$grid.setSelectionRows(crossRows)
        } else {
          this.$grid.setSelectRow(crossRows[0])
        }
      }
    })
    this.$grid.$on('select-change', ({ data, row }) => {
      this.innerValue = row[this.idField]
    })
    this.$grid.$on('selection-change', ({ data, selection }) => {
      this.innerValue = this.getJoinValues(data, selection, this.valueIds)
    })
  },
  render (h) {
    return this.$slots.default
  }
}
</script>
